<?php

namespace App\Http\Controllers\Api\Users;

use App\Http\Controllers\Controller;
use App\Models\Users;
use App\Models\UsersFriends;
use App\Models\UsersFriendsApplication;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    /**
     * 我的名片
     *
     * @return array
     */
    public function businessCard(): array
    {
        $user = auth('api')->user();
        unset($user['deleted_at']);
        unset($user['created_at']);
        unset($user['updated_at']);
        $data = $user;
        $result = [
            'data'=>$data
        ];
        return ret($result);
    }

    /**
     * 更新名片
     * @return array
     */
    public function updateBusinessCard(): array
    {
//        $post = request()->all();
        $post = request()->only(['mobile','career','workplace','profession','post']);
        $user = auth('api')->user();
        DB::beginTransaction();
        try {
            Users::query()->where('id',$user['id'])->update($post);
            DB::commit();
            return ret('更新成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 获取用户信息
     *
     * @return array
     */
    public function getUserInfo(): array
    {
        $user = auth('api')->user();

        if($user['avatar']){
            $user['avatar'] = getImageUrl( $user['avatar'] );
        }
        $result = [
            'data'=>$user
        ];
        return ret($result);
    }

    /**
     * 实名认证
     *
     * @return array
     */
    public function authentication(): array
    {
        $user = auth('api')->user();
        $info = request()->only('name','id_card');

        //验证身份证号码
        $return = validateIDCard($info['id_card']);
        if(!$return){
            return retError('身份证号码不正确');
        }

        DB::beginTransaction();
        try {
            Users::query()->where('id',$user['id'])->update($info);
            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 更新用户信息
     *
     * @return array
     */
    public function updateUserInfo(): array
    {
        $user = auth('api')->user();

        $post = request()->only('avatar','openid'
            ,'mobile','email'
            ,'college','major','school_level','habitation','name','username'
            ,'career','workplace','profession','post','id_card'
            ,'wechat','work_location'
        );

        DB::beginTransaction();
        try {
            Users::query()->where('id',$user['id'])->update($post);
            DB::commit();
            return ret('更新成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 校友卡申请接口
     *
     * @return array
     */
    public function alumniCardSign(): array
    {
        //$post = request()->all();
        $post = request()->only('username','openid'
            ,'username','mobile','name','email','degree'
            ,'school_time','college','major','school_level','habitation'
            ,'career','workplace','profession','post','id_card'
            ,'wechat','work_location'
        );
        $user = auth('api')->user();
        DB::beginTransaction();
        try {
            $post['is_alumni'] = 2;
            $post['sign_at'] = date("Y-m-d H:i:s",time());

            Users::query()->where('id',$user['id'])->update($post);
            DB::commit();
            return ret('认证成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 申请交换名片
     *
     * @return array
     */
    public function changeBusinessCard(): array
    {
        $user = auth('api')->user();
        $change_user_id = request('user_id',null);
        if(!$change_user_id){
            return retError('缺少交换用户');
        }
        $message = request('message',null);
        if(!$message){
            return retError('缺少交换留言');
        }
        //判断是否是与自己交换
        if($change_user_id  == $user['id']){
            return retError('不可与自己交换名片');
        }
        //判断是否已经交换过名片了
        $where['user_id'] = $change_user_id;
        $where['friends_id'] = $user['id'];
        $fCount =  UsersFriendsApplication::query()->where($where)->count();
        if($fCount > 0){
            //
            return retError('已交换过名片');
        }


        $create_data = [
            'user_id'=>$change_user_id,
            'friends_id'=>$user['id'],
            'message'=>request('message',''),
        ];
        DB::beginTransaction();
        try {
            UsersFriendsApplication::query()->create($create_data);

            Users:: query()->where('id',$change_user_id)->update(['is_unread_application'=>1]);
            Users:: query()->where('id',$user['id'])->update(['is_unread_application'=>1]);

            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 名片列表
     * 申请列表
     * @return array
     *
     * 我发起的
     */
    public function initiateForCardLists(): array
    {
        $user_id = auth('api')->id();
        $where = [
            'friends_id'=>$user_id
        ];

        $image_path = 'https://alumnus.biaoxufilm.com/storage/file/20231129210449.png';
        $friends = UsersFriendsApplication::query()->where($where)->with(['initiateFriends'])->latest()->get();
        $data = array();
        if($friends){
            foreach ($friends as $key=>$val){
                $data[] = [
                    'id'=>$val['id'],
                    'user_id'=>$val['user_id'],
                    'message'=>$val['message'],
                    'result'=>$val['result'],
                    'created_at'=> date("Y-m-d H:i:s",strtotime( $val['created_at'])),
                    'username'=>$val['initiateFriends']['username'],
                    'avatar'=>empty($val['initiateFriends']['avatar']) ? $image_path : getImageUrl($val['initiateFriends']['avatar']),
                ];
            }
        }
        $result = [
            'data'=>$data
        ];
        Users:: query()->where('id',$user_id)->update(['is_unread_application'=>0]);
        return ret($result);
    }

    /***
     * @return mixed
     *    我收到的
     */
    public function businessCardLists(): array
    {
        $user_id = auth('api')->id();
        $where = [
            'user_id'=>$user_id
        ];
        $image_path = 'https://alumnus.biaoxufilm.com/storage/file/20231129210449.png';
        $friends = UsersFriendsApplication::query()->where($where)->with(['friends'])->latest()->get();
        $data = array();
        if($friends){
            foreach ($friends as $key=>$val){
                $data[] = [
                    'id'=>$val['id'],
                    'user_id'=>$val['friends_id'],
                    'friends_id'=>$val['user_id'],
                    'message'=>$val['message'],
                    'created_at'=> date("Y-m-d H:i",strtotime($val['created_at'])),
                    'result'=>$val['result'],
                    'username'=>$val['friends']['username'],
                    'avatar'=>empty($val['friends']['avatar'])? $image_path : getImageUrl($val['friends']['avatar']) ,
                ];
            }
        }
        $result = [
            'data'=>$data
        ];

        Users:: query()->where('id',$user_id)->update(['is_unread_application'=>0]);
        return ret($result);
    }

    /**
     *  名片夹列表  只显示成功交换的校友名片
     *
     * @return array
     */
    public function SuccessCardLists(): array
    {
        $user_id = auth('api')->id();
        $where = [
            'user_id'=>$user_id,
            'is_block' => 2,
        ];
        $friends = UsersFriends::query()->where($where)->with(['friendsList'])->latest()->get();
        $data = array();
        if($friends){
            foreach ($friends as $key=>$val){
                $data[] = [
                    'id'=>$val['id'],
                    'user_id'=>$val['friends_id'],
                    'name'=>$val['friendsList']['name'],
                    'username'=>$val['friendsList']['username'],
                    'avatar'=>$val['friendsList']['avatar'],
                    'school_time'=>$val['friendsList']['school_time'],  //在校时间
                    'major'=>$val['friendsList']['major'],   //专业
                    'email'=>$val['friendsList']['email'],   //
                    'mobile'=>$val['friendsList']['mobile'],   //
                    'wechat'=>$val['friendsList']['wechat'],   //
                ];
            }
        }
        $result = [
            'data'=>$data
        ];
        return ret($result);
    }

    /**
     * 处理名片交换
     *
     * @return array
     */
    public function handleBusinessCard(): array
    {
        $user_id = auth('api')->id();
        $id = request('id',null);
        if(!$id){
            return retError('缺少必要参数');
        }
        $data = UsersFriendsApplication::query()->find($id);
        $feedback_message = request('message',null);
        $result =  request('result',2);
        DB::beginTransaction();
        try {
            UsersFriendsApplication::query()->where('id',$id)->update([
                'result'=>$result,
                'result_handle_at'=>Carbon::now(),
                'feedback_message'=>$feedback_message,
            ]);

            $whereA['user_id'] = $user_id;
            $whereA['friends_id'] = $data['friends_id'];
            $countA = UsersFriends::query()->where($whereA)->count();
            if($countA <= 0){
                UsersFriends::query()->create([
                    'user_id'=>$user_id,
                    'friends_id'=>$data['friends_id'],
                ]);
            }

            $whereB['friends_id'] = $user_id;
            $whereB['user_id'] = $data['friends_id'];
            $countB = UsersFriends::query()->where($whereB)->count();
            if($countB <= 0){
                UsersFriends::query()->create([
                    'user_id'=>$data['friends_id'],
                    'friends_id'=>$user_id,
                ]);
            }
            DB::commit();
            return ret('已同意');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 拉黑（名片）
     * @return array
     */
    public function friendsBlock(): array
    {
        $user_id = auth('api')->id();
        $friends_id = request('user_id',null);
        $where = [
            'user_id'=>$user_id,
            'friends_id'=>$friends_id,
        ];
        $is_block = 1;
        $is_cancel = request('is_cancel',2);#1-是，2-否
        if($is_cancel == 1){
            $is_block = 2;
        }
        DB::beginTransaction();
        try {
            UsersFriends::query()->where($where)->update([
                'is_block'=>$is_block
            ]);
            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * @return mixed
     * 获取校友名片
     */
    public function  getCardInfo():array
    {
        $user_id = request('user_id',null);
        if(!$user_id){
            return retError('缺少必要参数');
        }

        $data = DB::table('users')->where('id',$user_id)->select('id','avatar','name','id_card','username','degree','school_time','college','school_level','career',"mobile",'email','major','workplace','profession','post')->first();
        if(!$data){
            return retError('用户不存在或已注销');
        }
        $data = json_encode($data);
        $data = json_decode($data,true);
        $data['avatar'] = empty(getImageUrl($data['avatar'])) ? 'https://alumnus.biaoxufilm.com/storage/file/20231129210449.png' : getImageUrl($data['avatar']);
        $result = [
            'data'=>$data
        ];
        return ret($result);
    }

    /**
     * @return mixed
     * 校友列表
     */
    public function  alumniList(Request $request) :array
    {

        $user = auth('api')->user();
        if(!$user['id']){
            return retError('缺少必要参数');
        }

        $where = [];

        $orderBy = '';
        $type = request('type',null);            // 同城
        if ($type) {
            switch ($type)
            {
                case 1:          //推荐
                        $orderBy = 'created_at';
                      break;
                case 2:         //全部
                        $orderBy = 'id';
                      break;
                case 3:         //同城

                    $user_habitation = $user['habitation'];
                    if(!empty($user_habitation)){
                        $user_habitation =  mb_strstr($user_habitation,0,2);
                        $where[] = ['habitation','like',"$user_habitation%"];
                    }
                        break;
                case 4:         //同行

                    $profession = $user['profession'];
                    $where[] = ['profession','like',"$profession%"];
                        break;
                case 5:         //同院

                    $college = $user['college'];
                    $where['college'] = $college;
                        break;
                default:

            }
        }

        $name = request('name',null);                  // 按名称搜索
        if ($name) {
            $where[] = ['name','like',"%$name%"];
        }

        $college = request('college',null);                  // 按学院名称搜索
        if ($college) {
            $where['college'] = $college;
        }

        $page = request('page',1);    //页数
        $limit =  request('limit',2);  //每页显示条数
        $offset = ($page - 1) * $limit; //偏移量


        $count = Users::query()
            ->where($where)
            ->where('id','<>',$user['id'])
            ->count();

        $data =  Users::getList($where,$offset,$limit,$orderBy);
/*        $data = Users::query()
            ->where($where)
            ->latest('created_at')
            ->latest('id')
            //->paginate($limit,'*','page',$page)->toarray();
            ->offset($offset)->limit($limit)
            ->get();*/

        $total_pages = ceil(($count + $page-1) / $limit);

        $result = array();
        $return = array();
        if($data){
            foreach ($data as$val){
                $result[] = Users::getDataByID($val['id']);
            }
        }
        $return['result'] = $result;
        $return['count'] = $count;
        $return['page'] = $page;
        $return['total_pages'] = $total_pages;

        return ret($return);
    }

    public function menuList(Request $request) :array
    {

        $return = array();

        $return[0]['name'] =  '推荐';
        $return[0]['type'] =  '1';

        $return[1]['name'] =  '全部';
        $return[1]['type'] =  '2';

        $return[2]['name'] =  '同城';
        $return[2]['type'] =  '3';

        $return[3]['name'] =  '同行';
        $return[3]['type'] =  '4';

        $return[4]['name'] =  '同院';
        $return[4]['type'] =  '5';


        return ret($return);
    }

}
